using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for UserUtils
/// </summary>
public static class UserUtils
{
    /// <summary>
    /// Get current logged in user (check in session first, then reload from database)
    /// </summary>
    public static UserAcc CurrentUser
    {
        get
        {
            HttpContext context = HttpContext.Current;
            if (context.Session["User"] != null) return (context.Session["User"] as UserAcc);

            string loggedID = GetLoggedID();
            if (loggedID == "") return null;

            UserAcc acc = new UserAccBus().GetDto(loggedID);
            context.Session["User"] = acc;
            return acc;
        }
        set
        {
            HttpContext context = HttpContext.Current;
            context.Session["User"] = value;
        }
    }

    /// <summary>
    /// Get logged in UserID in cookie
    /// </summary>
    public static string GetLoggedID()
    {
        string loggedID = "";
        HttpRequest Request = HttpContext.Current.Request;
        if (Request.Browser.Cookies && Request.Cookies["UserLogin"] != null)
        {
            loggedID = Request.Cookies["UserLogin"].Value;
        }
        return loggedID;
    }

    public static void ValidateLogin()
    {
        HttpContext context = HttpContext.Current;
        HttpRequest Request = context.Request;
        HttpResponse Response = context.Response;

        string loggedID = GetLoggedID();
        if (loggedID == "")
        {
            context.Session["lastUrl"] = Request.Url;
            Response.Redirect("login.aspx");
        }
    }
}
